package com.eaero.conf;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;

/**
 * @author luofeng
 * @create 2023/4/7 9:44
 */
@Configuration
public class MailConfig {

    @Value("${email.host}")
    private String host;
    @Value("${email.port}")
    private Integer port;
    @Value("${email.from}")
    private String from;
    @Value("${email.user}")
    private String user;
    @Value("${email.pass}")
    private String pass;
    @Value("${email.private-key}")
    private String privateKey;
    @Bean
    public MailAccount getMailAccount() {
        MailAccount testMailAccount = new MailAccount();
        testMailAccount.setHost(host);
        testMailAccount.setPort(port);
        testMailAccount.setAuth(true);
        testMailAccount.setFrom(from);
        testMailAccount.setUser(user);

        RSA rsa = new RSA(privateKey, null);
        byte[] decrypted = rsa.decrypt(pass, KeyType.PrivateKey);
        testMailAccount.setPass(StrUtil.str(decrypted, StandardCharsets.UTF_8));

        testMailAccount.setSslEnable(true);
        testMailAccount.setSocketFactoryClass("javax.net.ssl.SSLSocketFactory");
        testMailAccount.setSocketFactoryFallback(true);
        testMailAccount.setSocketFactoryPort(port);
        testMailAccount.setConnectionTimeout(5000);
        return testMailAccount;
    }
}
